package com.ys.controller.web.storage;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.storage.TccOnlinePurchaseReturn;
import com.ys.entity.storage.TccOnlinePurchaseReturnItem;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 采购付款
 */
@Controller
@RequestMapping("/web/storage/tccOnlinePurchaseReturn")
public class WebTccOnlinePurchaseReturnController {
	private static final Logger logger = LoggerFactory.getLogger(WebTccOnlinePurchaseReturnController.class);

	@Autowired
	private CommonApiService<TccOnlinePurchaseReturn> commonApiService;

    @Autowired
    private YspTaskService yspTaskService;

    private final Long MENU_ID = MenuId.TCC_OnlinePurchaseReturn;
    private final Long MENU_ID1 = MenuId.TCC_OnlinePurchaseReturnSp;


    /*
     * 新增
     */
    @GetMapping("/toAdd")
    public String toAdd(Model model, HttpServletRequest request, HttpServletResponse response, String goodsIds) {
        try {
            TccOnlinePurchaseReturn entity = new TccOnlinePurchaseReturn();
            String bid = commonApiService.getCommonNextBid(MENU_ID);
            entity.setBid(bid);
            entity.setCreateTime(new Date());
            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID,new ArrayList<>());
            commonApiService.toAdd(model, entity, MENU_ID, null, subGridConfig);
            return "storage/tccOnlinePurchaseReturn/toAdd";
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 审核
     */
    @GetMapping("/toEdit")
    public String toEdit(Model model, HttpServletRequest request, HttpServletResponse response,
                         String bid){
        if (bid == null || bid.length() == 0) {
            return W.error(model, "单号不能为空");
        }

        try {

            Map<String, Object> entity = new TccOnlinePurchaseReturn()
                    .addLeftJoin("TCG_PurchaseByOrder AA ON A.purchaseOrderId = AA.id")
                    .addField("FORMAT(AA.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByOrder")//创建时间
                    .addField("FORMAT(AA.AuditingTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTimeByOrder")//订单审核时间
                    .addField("AA.OrderStatus AS orderStatus")//采购管理状态
                    .addField("AA.id AS purchaseOrderId")//采购完成单id
                    .addField("AA.bid AS purchaseOrderBid")//采购完成单号
                    .addField("AA.SpBm AS spBm")//商品编码
                    .addField("AA.AliAccount AS aliAccount")//1688账号
                    .addField("AA.AliOrderNumber AS aliOrderNumber")//1688订单编号
                    .addField("AA.AliMessage AS aliMessage")//1688留言
                    .addField("AA.AliState AS aliState")//1688订单状态
                    .addField("AA.OrderAmount AS orderAmount")//实际订单金额（含运）
                    .addField("AA.FreightCharge AS freightCharge")//实际运费
                    .addField("AA.ServiceCharge AS serviceCharge")//采购服务费
                    .addField("AA.Vgsbm AS vgsbm")//运营公司编码
                    .addField("AA.AliLogisticsPlace + AA.AliLogisticsBillNo AS remark1")//物流信息

                    .addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = AA.PlanBid")//采购计划表
                    .addField("H.bid AS purchasePlanBid")//采购计划单号
                    .addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = AA.Vgsbm ")//运营公司管理表
                    .addField("E.Vgsjc AS vgsjc")//采购公司简称
                    .addField("E.Vgsmc AS vgsmc")//采购公司名称
                    .addLeftJoin("TCG_PurchaseOrderPay AAP ON AAP.purchaseOrderBid = AA.bid")
                    .addField("AAP.bid AS purchaseOrderPayBid")//采购付款单号
                    .addField("AAP.vyhzh")//付款账户编码
                    .addField("AAP.vyhzhmc")//付款账户名称
                    .addField("AAP.vid")//账户编码
                    .addField("AAP.vkhh")//付款开户行
                    .addField("AA.id AS purchaseOrderId")//采购完成单id
                    .addField("AAP.chargeTroubleWf + AAP.chargeTrouble AS commissionCharge")//手续费 1688付款手续费+WF付款手续费
                    .addField(" CASE WHEN AAP.payType = 0 THEN '支付宝' ELSE '跨境宝' END AS payTypeName")//付款方式
                    .addField(" A.refundPayType refundPayTypeTo")//退款方式
                    .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                    .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

                    .setBid(bid)
                    .queryFirstMap();

            Long id = Long.valueOf(entity.get("id").toString());

            // 子列表配置信息
            List<Map<String, Object>> sonlist = new TccOnlinePurchaseReturnItem()
                    .addLeftJoin("TCG_PurchaseByOrderSon AAS ON AAS.id = A.purchaseOrderSonId")
                    .addField("AAS.subCode AS subCode")//子件编码
                    .addField("AAS.sku")//SKU属性
                    .addField("AAS.goodsId")//1688商品采购ID
                    .addField("AAS.skuId")//SKUID
                    .addField("AAS.specId")//SPECID
                    .addField("AAS.realityPrice")//子件实际单价
                    .addField("AAS.subRealityPrice")//子件采购单价
                    .addLeftJoin("TCG_PurchaseByOrder AA ON AAS.pid = AA.id")
                    .addLeftJoin("TP_ProductBasis G ON G.Code = AA.SpBm ")//商品母件信息表
                    .addField("G.Name AS spName")//商品名称
                    .addField("AA.SpBm AS spBm")//商品编码
                    .addLeftJoin("TCG_PurchaseByPlanSon J ON J.Id = AAS.PurchasePlanSonId ")//计划单子件信息表
                    .addField("J.SubName AS subName")//子件商品名称
                    .addField("J.SubAmount AS subAmount")//子件BOM数量
                    .addField("J.PurchaseAmount AS purchaseAmount")//子件采购数量=母件采购数量*子件数量
                    .addField("J.JgSl AS jgSl")//子件加购数量
                    .addField("J.SubTotalAmount AS subTotalAmount")//子件采购总数
                    .setPid(id)
                    .queryMap();
            Integer flowState = yspTaskService.flowState(bid);
            Long menuId = MENU_ID;
            if (flowState == 1) {
                menuId = MENU_ID1;
            }
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(menuId, sonlist);

            commonApiService.toEdit(model, id, new TccOnlinePurchaseReturn(), menuId, entity, subGridConfig);
            return "storage/tccOnlinePurchaseReturn/toEdit";
        } catch (Exception e) {
            e.printStackTrace();
            return W.error(model, e.getMessage());
        }
    }

}






